package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"infohub/cache"
	"infohub/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	desc := c.PostForm("desc")
	author := c.PostForm("author")
	if title == "" || desc == "" || author == "" {
		c.JSON(200, gin.H{
			"message": "参数不能为空",
			"code":    200,
		})
		return
	}
	article := models.Article{
		Title:  title,
		Desc:   desc,
		Author: author,
	}
	err := models.DB.Create(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"message": "添加失败",
			"code":    500,
		})
		return
	}
	c.JSON(200, gin.H{
		"message": "添加成功",
		"code":    200,
		"data":    article,
	})
	return
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var lists []models.Article
	redis_list_key := "article_list_" + c.Query("page")
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		models.DB.Offset(offset).Limit(size).Find(&lists)
		jsonData, _ := json.Marshal(lists)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &lists)
	}
	var count int64
	models.DB.Model(&models.Article{}).Count(&count)

	c.JSON(200, gin.H{
		"message": "展示成功",
		"code":    200,
		"list":    lists,
		"count":   count,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var detail models.Article
	redis_detail_key := "article_detail_" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_detail_key).Result()
	if result == "" {
		models.DB.Where("id = ?", id).First(&detail)
		jsonData, _ := json.Marshal(detail)
		cache.Rdb.Set(cache.Ctx, result, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &detail)
	}

	c.JSON(200, gin.H{
		"message": "展示成功",
		"code":    200,
		"data":    detail,
	})
	return
}

func Del(c *gin.Context) {
	id := c.PostForm("id")
	err := models.DB.Delete(&models.Article{}, id).Error
	if err != nil {
		c.JSON(200, gin.H{
			"message": "删除失败",
			"code":    200,
		})
		return
	}
	c.JSON(200, gin.H{
		"message": "删除成功",
		"code":    200,
	})
	return
}

func Page(c *gin.Context) {
	//defaultQuery是在值为空时传递一个默认值
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var list []models.Article

	redis_page_key := "article_page" + c.Query("page")
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_page_key).Result()
	if cacheData == "" {
		models.DB.Offset(offset).Limit(size).Find(&list)
		//数据转换为json格式
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_page_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	var total int64
	models.DB.Model(&models.Article{}).Count(&total)
	c.JSON(200, gin.H{
		"message": "展示成功",
		"code":    200,
		"data":    list,
		"total":   total,
	})
	return
}
